<template>
  <a-drawer
    title="编辑仓库入库"
    :maskClosable="false"
    width=80%
    placement="right"
    :closable="false"
    @close="onClose"
    :visible="budgetEditVisiable"
    style="height: calc(100% - 55px);overflow: auto;padding-bottom: 53px;">
    <a-form :form="form" layout="horizontal">
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='单据日期'
                       v-bind="formItemLayout"
                       :help="help">
            <vue-datepicker-local v-model="billDate" format="YYYY-MM-DD" style="display: block"></vue-datepicker-local>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='厂家'
                       v-bind="formItemLayout">
            <a-input v-model="supper"
                     v-decorator="['supper',{rules: [{ required: true, message: '厂家不能为空'}]}]"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='保管员'
                       v-bind="formItemLayout">
            <a-input v-model="storeKeeper"
                     v-decorator="['storeKeeper',{rules: [{ required: true, message: '保管员不能为空'}]}]"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='部门单位' v-bind="formItemLayout">
            <a-tree-select
              :allowClear="true"
              :dropdownStyle="{ maxHeight: '220px', overflow: 'auto' }"
              :treeData="deptTreeData"
              v-decorator="['deptId',{rules: [{ required: true, whitespace: true, message: '单位不能为空', }]}]"
              @change="onDeptChange">
            </a-tree-select>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='仓库列表' v-bind="formItemLayout">

            <a-select
              :allowClear="true"
              :dropdownStyle="{ maxHeight: '220px', overflow: 'auto' }"
              v-decorator="['storeCode',{rules: [{ required: true, whitespace: true, message: '仓库不能为空', }]}]"
            >
              <a-select-option v-for="r in storeTreeData" :key="r.id">{{r.storeName}}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='类别' v-bind="formItemLayout">
            <a-tree-select
              :allowClear="true"
              :dropdownStyle="{ maxHeight: '220px', overflow: 'auto' }"
              :treeData="planTypeTreeData"
              v-decorator="['typeId',{rules: [{ required: true, whitespace: true, message: '物资类别不能为空', }]}]"
              @change="onTypeChange">
            </a-tree-select>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <a-row>
      <div>
        <a-tabs defaultActiveKey="1">
          <a-tab-pane tab="入库详情" key="1">
            <a-button @click="newMember" type="primary" icon="plus" style="margin-top: 16px;margin-bottom:8px">编辑入库
            </a-button>
            <a-button @click="deleteMember" type="danger" :disabled="deleteDisabled" icon="delete" style="margin-top: 16px;margin-bottom:8px">删除</a-button>
            <a-table
              ref="table"
              size="middle"
              bordered
              rowKey="id"
              :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
              :columns="columns"
              :dataSource="dataSource">
              <template v-for="(col, i) in [ 'costSources','materialCode','materialsId','spe','unit','mnumber','price','amount','remarks','actualAmount','actualPrice']" :slot="col" slot-scope="text, record, index">
                <a-input
                  readOnly
                  :key="col"
                  v-if=" col=='materialCode' "
                  style="margin: -5px 0"
                  :value="gteDataSourceData(record.key).materialCode"
                  @change="e => handleChange(e.target.value, record.key, col)"
                />

                <a-input
                  readOnly
                  :key="col"
                  v-if=" col=='spe' "
                  style="margin: -5px 0"
                  :value="gteDataSourceData(record.key).spe"
                  @change="e => handleChange(e.target.value, record.key, col)"
                />
                <a-input
                  readOnly
                  :key="col"
                  v-if=" col=='unit' "
                  style="margin: -5px 0"
                  :value="gteDataSourceData(record.key).unit"
                  @change="e => handleChange(e.target.value, record.key, col)"
                />
                <a-input
                  :key="col"
                  v-if="col=='costSources'"
                  style="margin: -5px 0"
                  :value="gteDataSourceData(record.key).costSources"
                  @change="e => handleChange(e.target.value, record.key, col)"
                />
                <a-input
                  :key="col"
                  v-if="col=='remarks'"
                  style="margin: -5px 0"
                  :value="gteDataSourceData(record.key).remarks"
                  @change="e => handleChange(e.target.value, record.key, col)"
                />
                <a-input
                  :key="col"
                  v-if=" col=='price'"
                  style="margin: -5px 0"
                  :value="gteDataSourceData(record.key).price"
                  @change="e => handleChange(e.target.value, record.key, col)"
                />

                <a-input
                  :key="col"
                  v-if="col =='mnumber'"
                  style="margin: -5px 0"
                  :value="gteDataSourceData(record.key).mnumber"
                  @change="e => handleChange(e.target.value, record.key, col)"
                />
                <a-input
                  readOnly
                  :key="col"
                  v-if=" col=='amount' "
                  style="margin: -5px 0"
                  :value="gteDataSourceData(record.key).price*gteDataSourceData(record.key).mnumber"
                  @change="e => handleChange(e.target.value, record.key, col)"
                />

                <a-select :value="gteDataSourceData(record.key).materialsId"  v-if="col=='materialsId'" style="width: 120px"  @change="value => handleChange(value, record.key, col)">
                  <a-select-option v-for="(option, index) in projectList " :key="index" :value="option.id">{{option.materialName}}</a-select-option>
                </a-select>
                <a-input
                  :key="col"
                  v-if=" col=='actualPrice'"
                  style="margin: -5px 0"
                  :value="gteDataSourceData(record.key).price*gteDataSourceData(record.key).actualAmount"
                  @change="e => handleChange(e.target.value, record.key, col)"
                />
                <a-input
                  :key="col"
                  v-if=" col=='actualAmount' "
                  style="margin: -5px 0"
                  :value="text"
                  @change="e => handleChange(e.target.value, record.key, col)"
                />
              </template>

            </a-table>

          </a-tab-pane>
        </a-tabs>
      </div>
    </a-row>
    <div class="drawer-bootom-button">
      <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>

      <a-button v-if="this.billStatus ==1&& this.type ==3" @click="back">审批</a-button>
      <a-button v-else @click="handleSubmit" type="primary" :loading="loading">保存</a-button>
<!--      <process-back
        ref="processBack"
        @on-loading="processLoading=true"
        @on-loaded="processLoading=false"
        @handleBack="handleSubmit"
      />-->
    </div>
  </a-drawer>
</template>
<script>

import VueDatepickerLocal from 'vue-datepicker-local'
import moment from 'moment'

const formItemLayout = {
  labelCol: {span: 4},
  wrapperCol: {span: 15, offset: 2}
}
export default {
  name: 'annualBudgetGetAdd',
  components: {VueDatepickerLocal},
  props: {
    budgetEditVisiable: {
      default: false
    }
  },
  data () {
    return {
      budgetMonth: ' ',
      storeKeeper: '',
      supper: '',
      billDate: moment(new Date()).format('YYYY-MM-DD'),
      dataSource: [],
      loading: false,
      deptTreeData: [],
      storeTreeData: [],
      budgetInfotList: [],
      treeData: [],
      planTypeTreeData: [],
      typeTree: [],
      deptId: '',
      type: '',
      queryForm: {},
      storeCode: '',
      billStatus: '',
      typeValue: '',
      projectList: [],
      selectedRowKeys: [],
      materialPlanId: '',

      iExpandedKeys: [],
      form: this.$form.createForm(this),
      validateStatus: '',
      help: '',
      pagination: {
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      },
      formItemLayout: {
        labelCol: {
          xs: {span: 24},
          sm: {span: 4}
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 20}
        }
      },
      newMemberData: {
        key: '',
        costSources: '',
        materialCode: '',
        materialsId: '',
        spe: '',
        unit: '',
        mnumber: '',
        price: '',
        amount: '',
        remarks: '',
        actualAmount: '',
        actualPrice: ''
      }
    }
  },
  computed: {
    columns () {
      let {sortedInfo, filteredInfo} = this
      sortedInfo = sortedInfo || {}
      filteredInfo = filteredInfo || {}
      let objCol = [{
        title: '序号',
        width: 80,
        customRender: function (text, record, index) {
          return index + 1
        }
      }, {
        title: '费用来源',
        dataIndex: 'costSources',
        scopedSlots: { customRender: 'costSources' }
      }, {
        title: '材料编码',
        dataIndex: 'materialCode',
        scopedSlots: { customRender: 'materialCode' }
      }, {
        title: '材料名称',
        dataIndex: 'materialsId',
        scopedSlots: { customRender: 'materialsId' }
      }, {
        title: '材料规格',
        dataIndex: 'spe',
        scopedSlots: { customRender: 'spe' }
      }, {
        title: '单位',
        dataIndex: 'unit',
        scopedSlots: { customRender: 'unit' }
      }, {
        title: '单价',
        dataIndex: 'price',
        scopedSlots: { customRender: 'price' }
      }, {
        title: '数量',
        dataIndex: 'mnumber',
        scopedSlots: { customRender: 'mnumber' }
      }, {
        title: '金额',
        dataIndex: 'amount',
        scopedSlots: { customRender: 'amount' }
      }, {
        title: '备注',
        dataIndex: 'remarks',
        scopedSlots: { customRender: 'remarks' }
      }
      ]
      if (this.billStatus == 1 && this.type == 3) {
        objCol.push({
          title: '审核数量',
          dataIndex: 'actualAmount',
          scopedSlots: { customRender: 'actualAmount' }
        }, {
          title: '审批金额',
          dataIndex: 'actualPrice',
          scopedSlots: { customRender: 'actualPrice' }
        })
      }
      return objCol
    }
  },
  mounted () {
    this.loadTreeData()
  },

  methods: {
    moment,
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRows = selectedRows
      this.selectedRowKeys = selectedRowKeys
      if (selectedRowKeys.length > 0) {
        this.deleteDisabled = false
      } else {
        this.deleteDisabled = true
      }
    },
    deleteMember () {
      // 所有key
      let keys = []
      // 走后台删除的key
      let deleteArr = []
      this.selectedRows.forEach((row) => {
        keys.push(row.key)
        if (row.key.indexOf('new') < 0) {
          // 到台删除
          deleteArr.push(row.key)
        }
      })
      this.$delete('materialindetail', {ids: deleteArr.join(',')}).then((res) => {
        if (res.data.code == 200) {
          const newData = [...this.dataSource]
          this.dataSource = newData.filter(item => item.key.indexOf(keys) < 0)
        }
      })
    },
    setFormValues ({...record}, type, queryForm) {
      debugger
      let defaultValue = {}
      this.materialPlanId = record.id
      this.billDate = record.billDate
      this.deptId = record.deptId
      //  this.deptCode=record.deptCode;
      this.supper = record.supper
      this.storeKeeper = record.storeKeeper
      this.storeCode = record.storeCode
      this.typeId = record.typeId
      this.billStatus = record.billStatus
      this.type = type
      this.queryForm = queryForm
      defaultValue.billDate = record.billDate
      defaultValue.deptId = record.deptId

      defaultValue.supper = record.supper
      defaultValue.storeKeeper = record.storeKeeper
      defaultValue.typeId = record.typeId
      defaultValue.storeCode = record.storeCode

      Object.keys(defaultValue).forEach((key) => {
        this.form.getFieldDecorator(key)
        this.form.setFieldsValue(defaultValue)
        //  this.budgetMonth=defaultValue.budgetMonth;
      })

      this.$get('materialindetail/getDetailEdit', {materialPlanId: record.id}).then((res) => {
        this.loadProjectSelect()
        this.dataSource = res.data
      })
    },
    back () {
      let that = this
      this.$confirm({
        title: '确定提交所选中的记录?',
        content: '当您点击确定按钮后，这些记录将会被提交审核',
        centered: true,
        onOk () {
          let key = {'list': that.queryForm}
          that.$refs.processBack.show('materialin', key)
          that.billStatus = 2
        },
        onCancel () {
          that.selectedRowKeys = []
        }
      })
    },
    newMember () {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.newMemberData = {
            key: '',
            costSources: '',
            materialCode: '',
            materialsId: '',
            spe: '',
            unit: '',
            mnumber: '',
            price: '',
            amount: '',
            remarks: ''
          }
          this.newMemberData.key = Math.random().toString(36).substring(2) + ':new'
          this.dataSource.push(this.newMemberData)
        }
      })
    },
    handleChange (value, key, column) {
      const newData = [...this.dataSource]
      const target = newData.filter(item => key === item.key)[0]
      if (column.trim() == 'materialsId') {
        this.$get('materialsInfo/getOne', {'bid': value}).then((res) => {
          if (target) {
            target['materialCode'] = res.data.materialCode
            target['spe'] = res.data.spec
            target['unit'] = res.data.unit
            this.dataSource = newData
          }
        })
      }

      if (target) {
        target[column] = value
        this.dataSource = newData
      }
    },
    gteDataSourceData (key) {
      const newData = [...this.dataSource]
      const target = newData.filter(item => key === item.key)[0]
      if (target) {
        return target
      }
      return {}
    },

    loadProjectSelect () {
      this.$get('materialsInfo', {'type_id': this.typeId}).then((res) => {
        this.projectList = res.data.data
      })
    },

    onDeptChange (value, lable, extra) {
      this.maindeptName = lable
      this.deptId = value
      this.$get('dept/getOne', {'deptId': value}).then((res) => {
        //   this.newMemberData.billDate=moment(this.billDate).format('YYYY-MM-DD');
        //  this.newMemberData.deptCode=res.data.deptCode;
        // this.deptCode=res.data.deptCode;
        // this.newMemberData.deptId=value
      })
      // this.loadProjectSelect();
      this.deptId = value
    },
    onTypeChange (value, lable, extra) {
      this.mainTypeName = lable
      this.typeId = value
      this.$get('materialsType/getOne', {'typeId': value}).then((res) => {
        // this.newMemberData.budgetMonth=moment(this.budgetMonth).format('YYYY-MM');
        // this.newMemberData.materialCode=res.data.typeCode;
        this.typeName = res.data.typeName
        // this.newMemberData.typeId=value
      })
      this.loadProjectSelect()
      this.typeId = value
    },
    loadTreeData () {
      let that = this
      that.$get('projectType').then((res) => {
        for (let i = 0; i < res.data.rows.children.length; i++) {
          let temp = res.data.rows.children[i]
          that.setThisExpandedKeys(temp)
        }
        that.treeData = res.data.rows.children
        that.typeTree = res.data.rows.children
      })
    },
    setThisExpandedKeys (node) {
      if (node.children && node.children.length > 0) {
        this.iExpandedKeys.push(node.key)
        for (let a = 0; a < node.children.length; a++) {
          this.setThisExpandedKeys(node.children[a])
        }
      }
    },
    reset () {
      this.validateStatus = ''
      this.help = ''
      this.projectName = ''
      this.loading = false
      this.form.resetFields()
    },
    onClose () {
      this.dataSource = []
      this.form.resetFields()
      this.reset()
      this.$emit('close')
    },
    handleSubmit () {
      debugger
      this.form.validateFields((err, values) => {
        if (!err) {
          // values.deptName=this.maindeptName[0];
          // values.typeName=this.mainTypeName[0];
          values.id = this.materialPlanId
          values.billStatus = this.billStatus
          values.billDate = moment(this.billDate).format('YYYY-MM-DD')
          this.dataSource.forEach(item => {
            item.amount = item.price * item.mnumber
          })
          this.$post('materialIn/updateMaterialPlan', {'materialIn': JSON.stringify(values), 'listdetail': JSON.stringify(this.dataSource)}).then((res) => {
            if (res.data.code == 200) {
              this.dataSource = []
              this.form.resetFields()
              this.$emit('success')
            } else {
              this.$message.info('失败')
            }
          })
        }
      })
    }
  },
  // 监控值的改变
  watch: {
    budgetEditVisiable () {
      if (this.budgetEditVisiable) {
        this.$get('annualBudget/dept').then((r) => {
          this.deptTreeData = r.data.rows.children
        })
        this.$get('materialPlan/type').then((r) => {
          this.planTypeTreeData = r.data.rows.children
        })
        this.$get('storehouse/getStoreByName').then((r) => {
          this.storeTreeData = r.data.rows
        })
      }
    }
  }
}
</script>
